import { Client } from 'minio';
import { resolve } from 'path';
import { Readable } from 'stream';
var Fs = require('fs');

export const BucketName: string = 'public';

export class MinioClient {
  minioClient: Client;

  constructor() {
    this.minioClient = new Client({
      endPoint: process.env.MINIO_HOST,
      port: Number(process.env.MINIO_PORT),
      useSSL: Boolean(process.env.MINIO_USESSL),
      accessKey: process.env.MINIO_ACCESSKEY,
      secretKey: process.env.MINIO_SECRETKEY,
    });
  }

  uploadFile(fileName: string, fStream: Buffer, contentType = 'image/jpg') {
    const option = { 'Content-type': contentType };
    return this.minioClient.putObject(BucketName, fileName, fStream, option);
  }

  async uploadFileByPath(
    fileName: string,
    filePath: string,
    isDelete = true,
    format = 'image/jpg',
  ) {
    const option = { 'Content-type': format };

    var fileStream = Fs.createReadStream(filePath);
    var fileStat = Fs.statSync(filePath);
    if (fileStat.isFile()) {
      return new Promise((resolve) => {
        this.minioClient.putObject(
          BucketName,
          fileName,
          fileStream,
          fileStat.size,
          option,
          function (err, objInfo) {
            if (err) {
              resolve('error'); // err should be null
            }
            try {
              isDelete && Fs.unlinkSync(filePath);
              resolve('ok');
            } catch (error) {
              resolve('');
            }
          },
        );
      });
    }
  }

  presignedUrl(
    fileName: string,
    expiry: number = 24 * 60 * 60,
  ): Promise<string> {
    // return this.minioClient
    //   .presignedUrl('GET', BucketName, fileName, expiry)
    //   .then((res) => {
    //     if (res) {
    //       res = res.substring(
    //         0,
    //         res.indexOf('?') > -1 ? res.indexOf('?') : res.length,
    //       );
    //     }
    //     return res;
    //   });
    return new Promise((resolve) => {
      resolve(`https://minio.frp.hosea123.com/public/${fileName}`);
    });
  }
  getObject(fileName: string) {
    return this.minioClient.getObject(BucketName, fileName);
  }
  async remove(fileName: string) {
    console.log(fileName);
    try {
      await this.minioClient.removeObject(BucketName, fileName);
      await this.minioClient.statObject(BucketName, fileName);
    } catch (err) {
      console.error(`删除 ${fileName} 文件成功`);
      return null;
    }
  }
}
